<template>
  <!-- 相关方评定内容设置 -->
  <div class="relatedjudgeitem">
    <basic-container>
      <avue-crud
        :option="option"
        :table-loading="loading"
        :data="data"
        :page.sync="page"
        :permission="permissionList"
        :before-open="beforeOpen"
        v-model="form"
        ref="crud"
        @row-update="rowUpdate"
        @row-del="rowDel"
        @search-change="searchChange"
        @search-reset="searchReset"
        @selection-change="selectionChange"
        @current-change="currentChange"
        @size-change="sizeChange"
        @refresh-change="refreshChange"
        @on-load="onLoad"
      >
        <!-- 左上方菜单栏 -->
        <template slot="menuLeft">
          <el-button
            type="danger"
            size="small"
            icon="el-icon-delete"
            plain
            v-if="permission.relatedjudgeitem_delete"
            @click="handleDelete">
            删 除
          </el-button>
        </template>
      <!-- 二维码 -->
      <template slot="ewm" slot-scope="scope">
        <div>
          <el-button
            type="text"
            size="small"
            icon="el-icon-picture-outline"
            v-if="scope.row['ewm'] == 0 || scope.row['ewm'] == -1 || scope.row['ewm'] == '' || scope.row['ewm'] == undefined" @click="generateQRCode(scope.row['id'])">
            生成二维码
          </el-button>

          <el-button
            type="text"
            size="small"
            icon="el-icon-view"
            v-else
            @click="handleViewQRCode(scope.row)">
            查 看
          </el-button>
        </div>
      </template>
      <!-- 现场照片表格自定义 -->
      <template slot="xczp" slot-scope="scope">
        <div class="ope_row_div">
          <span v-if="scope.row['xczp'] === ''">-</span>
          <el-button v-else type="text" @click="handleViewPhoto(scope.row)">查看</el-button>
        </div>
      </template>
        <!-- 现场图片表单自定义 -->
        <template slot="xczpForm">
          <div v-if="dialogType !== 'view'">
            <el-button 
              size="small" 
              type="primary"
              @click="uploadXCZP">
              上传照片
            </el-button>
            <span style="margin-left: 10px; color: #606266; font-size: 12px;">只能上传图片，最多选择1张</span>
            <input 
              accept="image/*" 
              ref="xczpUpload" 
              id="xczpUpload" 
              style="display: none;" 
              type="file" 
              @change="xczpUpload" 
              multiple />
          </div>
        </template>

        <!-- 现场照片内容表单自定义 -->
        <template slot="xczpContentForm">
          <div class="xczp_content">
            <el-tag
              v-for="(item, index) in xczpFileList"
              :key="index"
              type="info" 
              :closable="dialogType !== 'view'" 
              @close="handleRemoveXCZP(index)"
            >
              <img 
                :src="item.response.data.fileUrl" 
                @click="previewXCZP(item)" 
                alt />
            </el-tag>
          </div>
        </template>
      </avue-crud>
      <!-- 弹窗：图片 -->
      <viewpicture
        :localPicBox="localPicBox"
        :localPictures="localPictures"
        :viewPicTitle="viewPicTitle"
        @confirmViewPicture="confirmViewPicture"
        @handleClosePicBox="handleClosePicBox">
      </viewpicture>
    </basic-container>
  </div>
</template>

<script>
import {
  generateQRCode,
  getQRCode,
  getList,
  update,
  remove,
  uploadFiles
} from "@/api/equipmentmanage/inspection/devicebindcode";
import { mapGetters } from "vuex";
import viewpicture from "../../saferisk/components/viewpicture.vue";
export default {
  components: {
    viewpicture
  },
  data() {
    return {
      form: {},
      query: {},
      data: [],
      loading: true,
      selectionList: [],
      page: {
        pageSize: this.$pageSize,
        currentPage: 1,
        total: 0
      },
      localPicBox: false,
      viewPicTitle: "",
      // 照片
      xczpFileList: [],
      option: {
        calcHeight: 30,
        dialogWidth: "30%",
        tip: false,
        searchShow: true,
        searchSpan: 5,
        searchMenuSpan: 4,
        border: true,
        index: false,
        selection: true,
        viewBtn: true,
        addBtn: false,
        refreshBtn: true,
        columnBtn: false,
        dialogClickModal: false,
        column: [
          {
            label: "设备名称",
            prop: "sbmc",
            align: "center",
            search: true,
            span:24,
            disabled:true
          },
          {
            label: "现场图片",
            prop: "xczp",
            align: "center",
            slot: true,
            span: 24,
            formslot: true,
          },
          {
            label: "",
            prop: "xczpContent",
            hide: true,
            span: 24,
            formslot: true
          },
          {
            label: "二维码",
            prop: "ewm",
            align: "center",
            display:false,
            row: false,
            slot: true,
            formslot: true,
            viewDisplay: false,
          },
        ]
      },
      
    };
  },
  computed: {
    ...mapGetters(["permission"]),

    // 按钮权限
    permissionList() {
      return {
        viewBtn: this.vaildData(this.permission.relatedjudgeitem_view, false),
        delBtn: this.vaildData(this.permission.relatedjudgeitem_delete, false),
        editBtn: this.vaildData(this.permission.relatedjudgeitem_edit, false)
      };
    },

    // 勾选项id
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  methods: {
    // 生成二维码
    generateQRCode(id) {
      this.$confirm("确定生成二维码?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        generateQRCode(id).then(res => {
          if (res.data.success) {
            this.$message.success("二维码生成成功!");
            this.page.currentPage = 1;
            this.onLoad(this.page);
          }
        });
      });
    },
    // 查看二维码
    handleViewQRCode(row) {
      getQRCode(row.ewm).then(res => {
        var resData = res.data.data;
        if (res.data.success && resData && resData.fileUrl) {
          this.localPictures = [resData];
          this.localPicBox = true;
          this.viewPicTitle = "二维码";
        }
      });
    },
    // 删除现场照片
    handleRemoveXCZP(index) {
      this.xczpFileList.splice(index, 1);
    },
    // 点击上传图片按钮
    uploadXCZP() {
      document.getElementById("xczpUpload").click();
    },
    // 上传现场照片
    xczpUpload(element) {
      console.log(element);
      if(this.$refs.xczpUpload.files.length + this.xczpFileList.length > 1) {
        this.$message.warning("最多上传1张现场图片!");
        this.$refs.xczpUpload.value = null;
        return;
      }
      let formData = {};
      let files = this.$refs.xczpUpload.files;
      formData = new FormData();
      for(let i = 0 ; i < files.length ; i++) {
        formData.append("files", files[i]);
      } 
      uploadFiles(formData).then(res => {
        if(!res.data.success) {
          return;
        }
        var resData = res.data.data;
        resData.forEach(item => {
          this.xczpFileList.push({
            name: item.fileName,
            response: {
              code: 200,
              msg: "操作成功",
              success: true,
              data: item
            }
          });
        });
        this.$refs.xczpUpload.value = null;
      });
    },
    // 确认照片
    confirmViewPicture() {
      this.localPictures = [];
      this.localPicBox = false;
      this.viewPicTitle = "";
    },
    // 关闭弹窗
    handleClosePicBox() {
      this.confirmViewPicture();
    },
    // 查看现场照片
    handleViewPhoto(row) {
      getQRCode(row.xczp).then(res => {
        var resData = res.data.data;
        if (res.data.success && resData && resData.fileUrl) {
          this.localPictures = [resData];
          this.localPicBox = true;
          this.viewPicTitle = "现场照片";
        }
      });
    },
    // 新增、查看、编辑弹窗打开前
    beforeOpen(done, type) {
      if(type === "add") {
        this.xczpFileList = [];
      } else {
        this.xczpFileList = [];
        if(this.form.xczp!=""){
          getQRCode(this.form.xczp).then(res => {
            var resData = res.data.data;
            this.xczpFileList.push({
              name: resData.fileName,
              response: {
                code: 200,
                data: resData,
                msg: "操作成功",
                success: true
              }
            });
          });
        }

      }
      this.dialogType = type;
      done();
    },
    // 修改
    rowUpdate(row, index, done) {
      for(let key in row) {
        if(key.indexOf("$") >= 0) {
          delete row[key];
        }
      }
      row.xczp = this.xczpFileList.length === 0 ? "" : this.formatPictureIds(this.xczpFileList);
      update(row).then(() => {
        this.onLoad(this.page);
        this.$message.success("操作成功!");
        done();
      });
    },
    // 获取现场照片ids
    formatPictureIds(filelist) {
      debugger
      var id = filelist[0].response.data.id
      return id;
    },
    // 删除一条
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    // 删除多条
    // handleDelete() {
    //   if (this.selectionList.length === 0) {
    //     this.$message.warning("请选择至少一条数据");
    //     return;
    //   }
    //   this.$confirm("确定将选择数据删除?", {
    //     confirmButtonText: "确定",
    //     cancelButtonText: "取消",
    //     type: "warning"
    //   })
    //     .then(() => {
    //       return remove(this.ids);
    //     })
    //     .then(() => {
    //       this.onLoad(this.page);
    //       this.$message({
    //         type: "success",
    //         message: "操作成功!"
    //       });
    //       this.$refs.crud.toggleSelection();
    //     });
    // },

    // 清空搜索条件
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },

    // 搜索条件改变
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },

    // 勾选
    selectionChange(list) {
      this.selectionList = list;
    },

    // 清空勾选
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },

    // 更换页数
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },

    // 更换每页显示数量
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },

    // 刷新
    refreshChange() {
      this.onLoad(this.page, this.query);
    },

    // 加载数据
    onLoad(page, params = {}) {
      this.loading = true;
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query)
      ).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.zp_content,
.xczp_content {
.el-upload-list__item {
    display: none !important;
  }

  .el-tag {
    height: 100px;
    line-height: 100px;
    padding: 0px 10px 0px 0px;
    margin-left: 0px;
    margin-top: 10px;
  }

  img {
    width: 98px;
    height: 98px;
    cursor: pointer;
  }
}
</style>